package com.ycsj.goldmedalnewconcept.common.activity;

import android.content.Intent;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.manager.PickChooseManager;
import com.ycsj.common.utils.RegexUtils;
import com.ycsj.goldmedalnewconcept.R;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.ZXingView;
import me.iwf.photopicker.PhotoPicker;

/**
 * 二维码扫描
 * Created by Administrator on 2019/5/9 0009.
 */

public class ScanQrCodeActivity extends BaseActivity implements QRCodeView.Delegate {
    @BindView(R.id.zxingview)
    ZXingView mZXingView;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_flashlight)
    TextView tvFlashlight;

    //从相册选择
    public static final int CHOOSEPICREQUESTCODE = 0x390;

    //控制闪光灯的开关
    private boolean isOpen;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_scan_code;
    }

    @Override
    protected void init() {

        initStateBar();

        //初始化标题
        initTitle();

        //设置监听
        initListener();
    }

    /**
     * 初始化标题栏
     */
    private void initTitle() {
        tvTitle.setText("二维码扫描");
    }

    /**
     * 设置扫描监听
     */
    private void initListener() {
        mZXingView.setDelegate(this);
    }


    @Override
    protected void onStart() {
        super.onStart();
        mZXingView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
        mZXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
    }

    @Override
    protected void onStop() {
        mZXingView.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        mZXingView.onDestroy(); // 销毁二维码扫描控件
        super.onDestroy();
    }

    /**
     * 震动
     */
    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    /**
     * 扫描的监听事件
     *
     * @param result
     */
    @Override
    public void onScanQRCodeSuccess(String result) {

        vibrate();

        //这里执行相关的业务代码逻辑
        if (TextUtils.isEmpty(result)) {
            ToastUtils.showShort("未识别到二维码");
        } else if (RegexUtils.isUrlAddress(result)) {
            //如果扫描到的是网站地址,则跳转到WebView界面
            WebViewActivity.goActivity(this, result);
        } else {
            //不是网址,直接吐司提示
            ToastUtils.showShort("扫描结果是:" + result);
        }

        finish();
    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {
        // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
        String tipText = mZXingView.getScanBoxView().getTipText();
        String ambientBrightnessTip = "\n环境过暗，请打开闪光灯";
        if (isDark) {
            if (!tipText.contains(ambientBrightnessTip)) {
                mZXingView.getScanBoxView().setTipText(tipText + ambientBrightnessTip);
            }
        } else {
            if (tipText.contains(ambientBrightnessTip)) {
                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip));
                mZXingView.getScanBoxView().setTipText(tipText);
            }
        }
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
//        Log.i("test", "打开相机出错");
        ToastUtils.showShort("打开相机出错");
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @OnClick({R.id.iv_back, R.id.lv_edit, R.id.tv_flashlight})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                //返回
                finish();
                break;
            case R.id.lv_edit:
                //选择相册
                choosePic();
                break;
            case R.id.tv_flashlight:
                //闪光灯
                controlFlashLight();
                break;
        }
    }

    /**
     * 从相册选取二维码
     */
    private void choosePic() {
        PickChooseManager.startPhotoPickActivity(this, 1, CHOOSEPICREQUESTCODE);
    }


    /**
     * 控制闪光灯开关
     */
    private void controlFlashLight() {
        if (isOpen) {
            // 关闭闪光灯
            mZXingView.closeFlashlight();
            tvFlashlight.setText("打开闪光灯");
        } else {
            //初次是flase
            // 打开闪光灯
            mZXingView.openFlashlight();
            tvFlashlight.setText("关闭闪光灯");
        }

        isOpen = !isOpen;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == CHOOSEPICREQUESTCODE) {
            if (data != null) {
                ArrayList<String> photos =
                        data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);

                //取出二维码的图片
                if (null != photos && photos.size() != 0) {
                    String qrPath = photos.get(0);
                    //调用通用的扫描
                    mZXingView.decodeQRCode(qrPath);
                }
            }
        }
    }
}
